package com.lf.task.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MyTaskScheduler implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private ScheduledExecutorService scheduledExecutorService;

    @PostConstruct
    private void init() {
        Map<String, Object> tasks = applicationContext.getBeansWithAnnotation(Task.class);
        // TODO 频率
        scheduledExecutorService = Executors.newScheduledThreadPool(tasks.size());

        for (Map.Entry<String, Object> entry : tasks.entrySet()) {
            Object task = entry.getValue();
            Task taskAnnotate = task.getClass().getAnnotation(Task.class);

//            log.info("registered task {}", entry.getKey());
            // TODO 优化
            scheduledExecutorService.scheduleAtFixedRate((Runnable) entry.getValue(), taskAnnotate.initialDelay(), taskAnnotate.period(),
                    TimeUnit.SECONDS);
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
